package com.fin.zw.aiqas.controller;

import com.fin.zw.aiqas.model.data.StatisticsDetailModel;
import com.fin.zw.aiqas.model.request.RuleStatisticsRequest;
import com.fin.zw.aiqas.model.request.StatisToServiceRequest;
import com.fin.zw.aiqas.model.response.QualityInfo;
import com.fin.zw.aiqas.model.response.RuleStatisticsResponse;
import com.fin.zw.aiqas.model.response.StatisticsToServiceResponse;
import com.fin.zw.aiqas.service.RuleStatisticsService;
import com.fin.zw.aiqas.util.CSVUtils;
import com.fin.zw.aiqas.util.FileUtil;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

@Controller
@RequestMapping("/ruleStatistics")
@Api(value = "质检规则命中统计", description = "质检规则命中统计")
public class RuleStatisticsController {

    private final static Logger log = LoggerFactory.getLogger(RuleStatisticsController.class);

    //质检规则统计
    @Autowired
    private RuleStatisticsService ruleStatisticsService;
    @Value("${file.filepath}")
    private String outPutPath;

    /**
     * 查询质检规则列表
     */
    @GetMapping("/fetchPageToRule")
    @ApiOperation(value = "质检规则命中统计", notes = "质检规则命中统计")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", dataType = "int", paramType = "query", value = "第几页（0 ... N）"),
            @ApiImplicitParam(name = "size", dataType = "int", paramType = "query", value = "每页的大小"),
            @ApiImplicitParam(name = "sort", dataType = "string", paramType = "query", allowMultiple = true, value = "排序：属性名（xxx，asc|desc）"),
    })
    public ResponseEntity<Page<RuleStatisticsResponse>> queryRuleStatistics(Pageable pageable, RuleStatisticsRequest request) {
        log.info("设置分页....");
        // 一共多少条
        int count = ruleStatisticsService.selectRuleStatisticsCount(request);
        PageHelper.startPage(pageable.getPageNumber() + 1, pageable.getPageSize());
        log.info("质检规则命中统计....");
        List<RuleStatisticsResponse> result = ruleStatisticsService.queryRuleStatistics(request);
        Page<RuleStatisticsResponse> pageResult = new PageImpl<>(result, pageable, count);
        log.info("质检规则命中统计完成!!!");
        return ResponseEntity.ok().body(pageResult);
    }

    @ApiOperation(value = "导出质检规则命中统计", notes = "导出质检规则命中统计")
    @GetMapping("/exportStatisticsRule")
    public void exportStatisticsRule(HttpServletResponse responses, RuleStatisticsRequest request) {
        LinkedHashMap<String, String> headMap = new LinkedHashMap<>();
        headMap.put("ruleTypeName", "规则分组名称");
        headMap.put("ruleName", "规则名称");
        headMap.put("frequency", "命中次数");
        headMap.put("total", "命中总数");
        headMap.put("percentage", "命中占比");
        headMap.put("serviceCount", "违规人次");
        List<RuleStatisticsResponse> result = ruleStatisticsService.queryRuleStatistics(request);
        List<LinkedHashMap> exportData = new ArrayList<>();
        result.forEach(response -> {
            LinkedHashMap<String, String> rowData = new LinkedHashMap<>();
            rowData.put("ruleTypeName", response.getRuleTypeName());
            rowData.put("ruleName", response.getRuleName());
            rowData.put("frequency", response.getFrequency().toString());
            rowData.put("total", String.valueOf(response.getTotal()));
            rowData.put("percentage", String.valueOf(response.getPercentage()));
            rowData.put("serviceCount", String.valueOf(response.getServiceCount()));
            exportData.add(rowData);
        });
        log.info("文件导出开始........");
        File csvFile = CSVUtils.createCSVFile(exportData, headMap, outPutPath, "download");
        FileUtil.download(responses, csvFile);
        csvFile.delete();
        log.info("文件制作完成开始下载........");
    }

    /**
     * 查询质检规则列表
     */
    @GetMapping("/fetchPageToCustomer")
    @ApiOperation(value = "客服统计", notes = "客服统计")
    public ResponseEntity<StatisticsToServiceResponse> queryCustomerServer(Pageable pageable, StatisToServiceRequest request) {
        log.info("客服统计....");
        StatisticsToServiceResponse result = ruleStatisticsService.queryCustomerServer(request);
        log.info("客服统计完成!!!");
        return ResponseEntity.ok().body(result);
    }

    @ApiOperation(value = "导出客服统计", notes = "导出客服统计")
    @GetMapping("/exportStatisticsService")
    public void exportStatisticsService(HttpServletResponse response, StatisToServiceRequest request) {
        StatisticsToServiceResponse result = ruleStatisticsService.queryCustomerServer(request);
        //表头
        LinkedHashMap<String, String> headMap = new LinkedHashMap<>();
        result.getHead().forEach(dynamicHeadModel -> {
            headMap.put(dynamicHeadModel.getId(), dynamicHeadModel.getName());
        });
        //数据
        List<LinkedHashMap<String, String>> exportData = result.getData();

        log.info("文件导出开始........");
        File csvFile = CSVUtils.createCSVFile(exportData, headMap, outPutPath, "download");
        FileUtil.download(response, csvFile);
        csvFile.delete();
    }


    @GetMapping("/qualityInfo")
    @ApiOperation(value = "质检概况统计", notes = "质检概况统计")
    public ResponseEntity<QualityInfo> qualityInfo() {
        QualityInfo qualityInfo = ruleStatisticsService.qualityInfo();
        return ResponseEntity.ok().body(qualityInfo);
    }


    @GetMapping("/statisticsRecord")
    @ApiOperation(value = "统计最近一个月，每天质检的录音数量", notes = "统计最近一个月，每天质检的录音数量")
    public ResponseEntity<List<StatisticsDetailModel>> statisticsRecord() {
        List<StatisticsDetailModel> list = ruleStatisticsService.statisticsRecord();
        return ResponseEntity.ok().body(list);
    }

    @GetMapping("/selectInspectionByRule")
    @ApiOperation(value = "统计每个规则出现的次数", notes = "统计每个规则出现的次数")
    public ResponseEntity<List<StatisticsDetailModel>> selectInspectionByRule() {
        List<StatisticsDetailModel> list = ruleStatisticsService.selectInspectionByRule();
        return ResponseEntity.ok().body(list);
    }
}
